/*
 * author      : 吴中勤 
 * date        : 2018/9/12
 * description : TODO
 */

package com.deepexi.adapter.config;

import com.deepexi.adapter.common.exception.HttpNon200Exception;
import com.deepexi.adapter.converter.sap.SapConverterContext;
import com.deepexi.adapter.sdk.sap.exception.SapBizException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Aspect
@Component
public class ServiceExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ServiceExceptionHandler.class);

    @Autowired
    private SapConverterContext sapConverterContext;
    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Before("@annotation(loggerManage)")
    public void addBeforeLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
        sapConverterContext.getLogContext().setKeyword1(loggerManage.description());

//        logger.info("执行--" + loggerManage.description() + "--开始");
        startTime.set(System.currentTimeMillis());
//        logger.info(joinPoint.getSignature().toString());
//        logger.info(parseParames(joinPoint.getArgs()));
    }

    @AfterReturning("@annotation(loggerManage)")
    public void addAfterReturningLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
//        logger.info("执行--" + loggerManage.description() + "--结束");
        logger.info("AfterReturning 执行时间--" + (System.currentTimeMillis() - startTime.get()));
    }

    @AfterThrowing(pointcut = "@annotation(loggerManage)", throwing = "ex")
    public void addAfterThrowingLogger(JoinPoint joinPoint, LoggerManage loggerManage, Exception ex) {
        logger.info("AfterThrowing 执行时间--" + (System.currentTimeMillis() - startTime.get()));

        if (ex instanceof IOException) {
            logger.error("网络异常处理", ex);
        } else if (ex instanceof JSONException) {
            logger.error("sap返回解析异常", ex);
        } else if (ex instanceof SapBizException) {
            logger.error("sap返回业务异常", ex);
        } else if (ex instanceof HttpNon200Exception) {
            logger.error("sap返回非200", ex);
        }
//        ex.printStackTrace();

        //        logger.error("执行--" + loggerManage.description() + "--异常", ex);
    }

//    private String parseParames(Object[] parames) {
//        if (null == parames || parames.length <= 0) {
//            return "";
//        }
//        StringBuffer param = new StringBuffer("参数--");
//        for (Object obj : parames) {
//            String va = ToStringBuilder.reflectionToString(obj);
//            param.append(va).append("  ");
//        }
//        return param.toString();
//    }

}
